import { ref, reactive } from 'vue'
import { logout, updatepassword } from '~/api/manager'
import { showModal, toast } from "~/composables/util"
import { useRouter } from "vue-router"
import { useStore } from "vuex";
export function useRepassword() {
    const store = useStore()
    const router = useRouter()
    const formDrawerRef = ref(null)
    const form = reactive({
        oldpassword: '',
        password: '',
        repassword: '',

    })

    const rules = {
        oldpassword: [
            { required: true, message: '旧密码不能为空', trigger: 'blur' },
        ],
        password: [
            { required: true, message: '新密码不能为空', trigger: 'blur' },
            // { min: 6, max: 10, message: '密码长度必须是6-10个字符', trigger: 'blur' },
        ],
        repassword: [
            { required: true, message: '确认密码不能为空', trigger: 'blur' },
            // { min: 6, max: 10, message: '密码长度必须是6-10个字符', trigger: 'blur' },
        ],
    }

    const formRef = ref(null)
    const openRePasswordForm = () => formDrawerRef.value.open()
    const onSubmit = () => {
        formRef.value.validate((validate) => {
            if (!validate) {
                return false
            }
            formDrawerRef.value.showLoading()
            updatepassword(form)
                .then(res => {
                    toast("修改密码成功，请重新登录")
                    store.dispatch('logout')
                    router.push("/login")
                })
                .finally(() => {
                    formDrawerRef.value.hideLoading()
                })
        })

    }

    return {
        formDrawerRef,
        form,
        rules,
        formRef,
        onSubmit,
        openRePasswordForm


    }
}

export function useLogout(){
    const store = useStore()
    const router = useRouter()
    function handleLogout() {
        showModal("是否要退出登录？").then(res => {
            logout().finally(() => {
                store.dispatch('logout')
                // 跳转回登录页
                router.push("/login")
                // 提示退出登录成功
                toast("退出登录成功")
            })
        })
    }
    return {
        handleLogout
    }
}